﻿namespace Practices.IdentityProvider {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.AspNet.Identity.Owin;
    using System.Configuration;

    public partial class LoginPage : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            if (!User.Identity.IsAuthenticated) {
                var account = Request.Headers[ConfigurationManager.AppSettings["IdentityHeader"]];
                if (string.IsNullOrEmpty(account)) {
                    Response.Redirect(ConfigurationManager.AppSettings["WebSealUrl"] + Constants.LoginPath);
                } else {
                    SignIn(account);
                }
            }
        }

        protected void LogIn(object sender, EventArgs e) {
            if (IsValid) {
                var loginName = txtAccount.Text.Trim();
                if (!string.IsNullOrEmpty(loginName)) {
                    SignIn(loginName);
                }
            }
        }
        
        protected void SignIn(string userName) {
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
            var user = new ApplicationUser() {
                UserName = userName
            };
            //signinManager.SignIn(user, isPersistent: false, rememberBrowser: false);
            var result = signinManager.PasswordSignIn(userName, password: "", isPersistent: false, shouldLockout: false);
            switch (result) {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], HttpContext.Current.Response);
                    break;
                default:
                    break;
            }
        }
    }
}